#ifndef DATABASEMANAGER_H
#define DATABASEMANAGER_H

#include <QDebug>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlQueryModel>

#include "User.h"
#include "PartStore.h"

/*=========================<换mySQL服务器需要配置此处>=========================*/
#define DBLinkageName "CAISystemLinkage"
#define DBHost "115.190.100.53"
#define DBName "CAIDatabase"
#define DBPort 3306
#define CDBUserName "minli-CMSIS"
#define CDBUserPassword "123456Lsn"

#define DataBaseManager_DEBUG 1//之后要调试其他功能的时候可以将这个设置为0，防止Debug信息太多

#define QUERY_IFERROR if(m_query.lastError().isValid())  \
{\
        qDebug() << "执行语句失败:" << m_query.lastError().text();\
        return;\
}

class DatabaseManager
{
public:
    static DatabaseManager* getInstance(void);
    void initDatabase(void);

    User login_getUserInfo(QString name,QString password);
    /*===========================<用户管理相关的sql处理函数>===========================*/
    qint64 userManage_insertUserInfoRecord(const User& userInfo);
    qint64 userManage_deleteUserInfoRecord(qint64 userId);
    qint64 userManage_updateUserInfoRecord(const User& newUserInfo, qint64 selectUserId);
    QSqlQuery userManage_findUserInfoRecord(QString name);
    /*===========================<日志记录管理相关的sql处理函数>===========================*/
    qint64 logManage_insertLogRecord(const LogEntry& logInfo);
    /*===========================<配件信息记录管理相关的sql处理函数>===========================*/
    qint64 partManage_insertPartInfoRecord(const Part& partInfo);
    qint64 partManage_deletePartInfoRecord(qint64 partId);
    qint64 partManage_updatePartInfoRecord(const Part& newUserInfo, qint64 selectUserId);
    QSqlQuery partManage_findPartInfoRecord(QString name);
    /*===========================<分配配件位置相关的sql处理函数>===========================*/
    qint64 allotManage_updateLocationInfoRecord(QString newLocation,qint64 partId);
    QSqlQuery allotManage_findPartInfoRecord(QString location);
    /*===========================<仓库出入库记录相关的sql处理函数>===========================*/
    qint64 IOManage_updateQuantityinfoRecord(qint64 newNum,qint64 partId);
    qint64 RecordManage_insertInRecordInfoRecord(const StoreInRecord& record);
    qint64 RecordManage_insertOutRecordInfoRecord(const StoreOutRecord& record);
    /*===========================<辅助函数>===========================*/
    QSqlQuery getQueryForAll(const QString& tableName);

    const QSqlDatabase& getDB(void);

    DatabaseManager(DatabaseManager&) = delete;
    DatabaseManager& operator=(DatabaseManager&) = delete;
private:
    DatabaseManager();

private:
    QSqlDatabase m_DB;
    QSqlQuery m_query;

    bool m_isFristInit = true;

    static DatabaseManager* m_instance;
};

#endif // DATABASEMANAGER_H
